package com.xiaochun.hxhj;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.adapter.AlreadyRecyclerViewAdapter;
import com.adapter.NoRecyclerViewAdapter;
import com.bean.AlreadyExpertBean;
import com.bean.NoExpertBean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.myview.CustomProgressDialog;
import com.myview.PullLoadMoreRecyclerView;
import com.util.ExitAppUtil;
import com.util.InfoEventMessage;
import com.util.MyLog;
import com.util.RequestManager;
import com.util.ToastUtils;

import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class JingxiaoshangActivity extends BaseActivity {


    private PullLoadMoreRecyclerView already_data;
    private PullLoadMoreRecyclerView no_data;
    private AlreadyRecyclerViewAdapter alreadyadapter;
    private NoRecyclerViewAdapter noadapter;
    private LinearLayoutManager layoutManager;
    private View loadMoreShopView;
    private View notMoreShopView;
    private CustomProgressDialog customProgressDialog;
    private int page = 1;
    private int pagecount = 20;
    private View bottomView;
    private String category_id = "";
    private String titlename;
    private String bannerid;
    private RelativeLayout rl_already_experd;
    private TextView tv_already_expert;
    private View view_already_expert;
    private RelativeLayout rl_no_experd;
    private TextView tv_no_expert;
    private View view_no_expert;
    private String istype = "0";//0已推广   1未推广
    private List<AlreadyExpertBean.DataBeanX.DataBean> alreadylisttemp = new ArrayList<>();
    private List<AlreadyExpertBean.DataBeanX.DataBean> alreadylist = new ArrayList<>();
    private List<NoExpertBean.DataBeanX.DataBean> nolisttemp = new ArrayList<>();
    private List<NoExpertBean.DataBeanX.DataBean> nolist = new ArrayList<>();
    private LinearLayout llay_load;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        customProgressDialog = new CustomProgressDialog(context, "", R.style.CommProgressDialog);
        WindowManager.LayoutParams params = customProgressDialog.getWindow().getAttributes();
        params.alpha = 0.7f;//取值为0-1之间  0是全透明，1是不透明
        params.dimAmount = 0f;   //取值为0-1之间  1是全黑
        customProgressDialog.getWindow().setAttributes(params);
        customProgressDialog.show();
    }

    @Override
    protected void initListener() {
        already_data.setOnPullLoadMoreListener(new PullLoadMoreRecyclerView.PullLoadMoreListener() {
            @Override
            public void onRefresh() {
                page = 1;
                MyLog.e("推广列表请求数据","已推广88");
                getData();
            }

            @Override
            public void onLoadMore() {
                if (alreadylist.size() >= 20){
                    page++;
                    MyLog.e("推广列表请求数据","已推广95");
                    getData();
                }else{
                    already_data.setPullLoadMoreCompleted();
                }
            }

            @Override
            public void onScrollChanged(int heightTotal) {

            }

            @Override
            public void onScrollState(int type) {

            }
        });
        no_data.setOnPullLoadMoreListener(new PullLoadMoreRecyclerView.PullLoadMoreListener() {
            @Override
            public void onRefresh() {
                page = 1;
                MyLog.e("推广列表请求数据","未推广113");
                getData();
            }

            @Override
            public void onLoadMore() {
                if (nolist.size() >= 30) {
                    page++;
                    MyLog.e("推广列表请求数据", "未推广120");
                    getData();
                }else{
                    no_data.setPullLoadMoreCompleted();
                }
            }

            @Override
            public void onScrollChanged(int heightTotal) {

            }

            @Override
            public void onScrollState(int type) {

            }
        });

        rl_already_experd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                istype = "0";//0已推广   1未推广
                //已推广
                loadMoreShopView.setBackgroundResource(R.color.colorFAFAFA);
                notMoreShopView.setBackgroundResource(R.color.colorFAFAFA);
                tv_already_expert.setTextColor(getResources().getColor(R.color.colorFF9D5E));
                view_already_expert.setVisibility(View.VISIBLE);
                already_data.setVisibility(View.VISIBLE);
                tv_no_expert.setTextColor(getResources().getColor(R.color.color333));
                view_no_expert.setVisibility(View.GONE);
                no_data.setVisibility(View.GONE);
                MyLog.e("推广列表请求数据","已推广145");
                page = 1;
                getData();
            }
        });
        rl_no_experd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                istype = "1";//0已推广   1未推广
                //未推广
                loadMoreShopView.setBackgroundResource(R.color.colorf2);
                notMoreShopView.setBackgroundResource(R.color.colorf2);
                tv_already_expert.setTextColor(getResources().getColor(R.color.color333));
                view_already_expert.setVisibility(View.GONE);
                already_data.setVisibility(View.GONE);
                tv_no_expert.setTextColor(getResources().getColor(R.color.colorFF9D5E));
                view_no_expert.setVisibility(View.VISIBLE);
                no_data.setVisibility(View.VISIBLE);
                MyLog.e("推广列表请求数据","未推广159");
                page = 1;
                getData();
            }
        });


    }

    @Override
    protected int initLayout() {
        return R.layout.activity_jingxiaoshang;
    }

    @Override
    protected void initView() {

        changeTitle("我的推广");

        rl_already_experd = findViewById(R.id.rl_already_experd);
        tv_already_expert = findViewById(R.id.tv_already_expert);
        view_already_expert = findViewById(R.id.view_already_expert);
        rl_no_experd = findViewById(R.id.rl_no_experd);
        tv_no_expert = findViewById(R.id.tv_no_expert);
        view_no_expert = findViewById(R.id.view_no_expert);

        already_data = findViewById(R.id.already_data);
        alreadyadapter = new AlreadyRecyclerViewAdapter(alreadylist, context, myapp);
        setHeader(already_data,"1");
        already_data.setAdapter(alreadyadapter);
        already_data.setLinearLayout();
        already_data.setRefreshing(true);
        layoutManager = (LinearLayoutManager) already_data.getLayoutManager();
        already_data.cancleAnimal();

        no_data = findViewById(R.id.no_data);
        noadapter = new NoRecyclerViewAdapter(nolist, context, myapp);
        setHeader(no_data,"2");
        no_data.setAdapter(noadapter);
        no_data.setGridLayout(2);
        no_data.setRefreshing(true);
        layoutManager = (LinearLayoutManager) no_data.getLayoutManager();
        no_data.cancleAnimal();
        loadMoreShopView = View.inflate(context, R.layout.item_moredata, null);
        notMoreShopView = View.inflate(context, R.layout.item_nodata, null);

        if ("0".equals(istype)){
            //已推广
            loadMoreShopView.setBackgroundResource(R.color.colorFAFAFA);
            notMoreShopView.setBackgroundResource(R.color.colorFAFAFA);
        }else if ("1".equals(istype)){
            //未推广
            loadMoreShopView.setBackgroundResource(R.color.colorf2);
            notMoreShopView.setBackgroundResource(R.color.colorf2);
        }



        initTopView();

        GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 2);

        //通过isTitle的标志来判断是否是title
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                int itemViewType = noadapter.getItemViewType(position);
                if (itemViewType == 6){
                    return 2;
                }else{
                    return 1;
                }
            }
        });
        gridLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        no_data.setGridLayout3(gridLayoutManager);
        MyLog.e("推广列表请求数据","已推广234");
        getData();
    }

    private void initTopView() {
        llay_load = bottomView.findViewById(R.id.llay_load);
    }

    /**
     * 设置头部布局
     *
     * @param view
     */
    private void setHeader(PullLoadMoreRecyclerView view,String type) {

        //底部加载更多
        bottomView = LayoutInflater.from(context).inflate(R.layout.main_bottom, view, false);
        if ("1".equals(type)){
            alreadyadapter.setBottomView(bottomView);
        }else if ("2".equals(type)){
            bottomView.setBackgroundResource(R.color.colorf2);
            noadapter.setBottomView(bottomView);
        }
    }

    @Override
    protected void initData() {

    }

    private void getData() {
        String token = sharedPreferences.getString("token", "");
        String url = "";
        if ("0".equals(istype)){
            //已推广
            url = myapp.getWebConfig() + "/api/vip/bindindex";
        }else if ("1".equals(istype)){
            //未推广
            url = myapp.getWebConfig() + "/api/vip/index";
        }

        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("page", page+"");
        if ("0".equals(istype)){
            //已推广
            paramsMap.put("limit", "20");
        }else if ("1".equals(istype)){
            //未推广
            paramsMap.put("limit", "30");
        }

        paramsMap.put("token", token);
        MyLog.e("未推广","page="+page);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONObject data = jsonObject.getJSONObject("data");


                    JSONArray databook = data.getJSONArray("data");
                    if ("0".equals(istype)){
                        alreadylisttemp.clear();
                        //已推广
                        alreadylisttemp = new Gson().fromJson(databook.toString(), new TypeToken<List<AlreadyExpertBean.DataBeanX.DataBean>>() {
                        }.getType());
                    }else if ("1".equals(istype)){
                        nolisttemp.clear();
                        //未推广
                        nolisttemp = new Gson().fromJson(databook.toString(), new TypeToken<List<NoExpertBean.DataBeanX.DataBean>>() {
                        }.getType());
                    }

                    msg.arg1 = 2;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handler.sendMessage(msg);
                }
            }
        });
    }
    public Handler handler = new Handler() {

        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    already_data.setPullLoadMoreCompleted();
                    no_data.setPullLoadMoreCompleted();
                    String obj = (String) msg.obj;
                    ToastUtils.show(obj);
                    break;
                case 1:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    ToastUtils.show(R.string.net_error);
                    already_data.setPullLoadMoreCompleted();
                    no_data.setPullLoadMoreCompleted();
                    break;
                case 2:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    llay_load.removeAllViews();
                    if ("0".equals(istype)){
                        if (page == 1){
                            alreadylist.clear();
                        }
                        alreadylist.addAll(alreadylisttemp);
                        alreadyadapter.setDatas(alreadylist);
                        already_data.setPullLoadMoreCompleted();
                        if (alreadylisttemp.size() == 0){
                            page--;
                        }
                        if (alreadylisttemp.size() < 20){
                            if (page > 1){
                                llay_load.addView(notMoreShopView);
                            }
                        }else{
                            llay_load.addView(loadMoreShopView);
                        }
                    }else if ("1".equals(istype)){
                        if (page == 1){
                            nolist.clear();
                        }
                        nolist.addAll(nolisttemp);
                        noadapter.setDatas(nolist);
                        no_data.setPullLoadMoreCompleted();
                        if (nolisttemp.size() == 0){
                            page--;
                        }
                        if (nolisttemp.size() < 30){
                            if (page > 1){
                                llay_load.addView(notMoreShopView);
                            }
                        }else{
                            llay_load.addView(loadMoreShopView);
                        }
                    }
                    break;
                case 3:

                    break;
                case 4:

                    break;
                case 11:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    sharedPreferences.edit().putString("user_id","").commit();
                    sharedPreferences.edit().putString("username","").commit();
                    sharedPreferences.edit().putString("nickname","").commit();
                    sharedPreferences.edit().putString("mobile","").commit();
                    sharedPreferences.edit().putString("avatar","").commit();
                    sharedPreferences.edit().putString("score","").commit();
                    sharedPreferences.edit().putString("student_id","").commit();
                    sharedPreferences.edit().putString("is_bind_wx","").commit();
                    sharedPreferences.edit().putString("token","").commit();
                    sharedPreferences.edit().putString("is_agent","").commit();
                    sharedPreferences.edit().putString("vip_expire","").commit();
                    sharedPreferences.edit().putString("is_vip","").commit();
                    break;
                case 12:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    break;
            }
        }
    };
    @Subscribe
    public void onEventMainThread(InfoEventMessage event) {
        String paymessage = event.getMessage();
        //0失败   1成功

        if ("设备ID已更新退出登录".equals(paymessage)){
            String type = event.getType();
            ExitAppUtil.getInstance().popbyexit(type,context,JingxiaoshangActivity.this,tv_already_expert);
//            popbyexit(type);
        }
    }

}
